<?php

namespace app\api\service;

use app\common\library\Email;
use think\Exception;
use think\Log;
use think\Request;
use think\Validate;

class EmsService extends Api
{
    protected static $instance;
    protected $logName = 'emailLog';

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
    }

    public static function getInstance()
    {
        if (is_null(self::$instance))
        {
            self::$instance = new static();
        }
        return self::$instance;
    }

    /**
     * 发送邮件
     * params: toEmail 收件箱   title 邮件标题
     */
    public function sendEmail($params)
    {
        $validate = new Validate([
            'toEmail' => 'require',
            'title' => 'require',
        ]);
        if (!$validate->check($params))
        {
            $this->error($validate->getError());
        }
        $status = true;$isZip = true;
        do{
            try{
                $isZip = isset($params['isZip']) && isset($params['files']) ? (!$params['isZip'] ? false : $isZip) : $isZip;

                $result = $this->send($params, $isZip);
                $status = !$result['result'];

                LogService::getInstance()->writeLogInfo($result, $this->logName);
            }catch (Exception $e)
            {
                LogService::getInstance()->writeLogInfo([
                    'errorInfo' => $e->getMessage()
                ], $this->logName);
            }
            if ($status)
            {
                sleep(15);
            }
        }while($status);
        return true;
    }

    public function send($params, $isZip = true)
    {
        $options = isset($params['options']) ? $params['options'] : [
            'mail_smtp_host' => 'smtp.163.com',
            'mail_smtp_port' => '465',
            'mail_smtp_user' => 'ruilubao@163.com',
            'mail_smtp_pass' => 'UFDUQEYQJRLDBGRB',
            'mail_verify_type' => '2',
            'mail_from' => 'ruilubao@163.com',
        ];

        $obj = Email::instance($options);

        $obj->subject($params['title'])//$params['title'])
            ->from('ruilubao@163.com')
            ->to($params['toEmail'])//$params['toEmail'])
            ->message($params['title'], false);

        $files = [];
        if (isset($params['files']))
        {
            $params['files'] = array_filter($params['files']);
            $fileName = isset($params['fileName']) ? $params['fileName'].time().rand(1000, 9999) : datetime(time(), 'YmdHis').rand(1000,9999);
            if ($isZip)
            {
                $zipFile = ZipService::getInstance()->createZip($params['files'], $fileName);
                $files = [$zipFile];
            }else{
                $files = $params['files'];
            }
        }

        if (!empty($files)) foreach ($files as $k => $v){
            $vFileName = explode('/', $v);
            $obj->attachment($v, end($vFileName));
        }
        $result = $obj->send();
        return [
            'result' => $result,
            'error' => $obj->getError()
        ];
    }
}